<template>
  <div class="blogcomment-container" v-loading="isLoading">
    <MessageArea
      :subTitle="`(共 ${data.total} 条评论)`"
      :list="data.rows"
      @submit="handleSubmit"
      :isListLoding="loadCommentMore"
    />
    <p v-if="noMore" class="nomore-text">没有更多了</p>
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData.js";
import { getBlogComment, postBlogComment } from "@/api/blog.js";
import { debounce } from "@/utils/tools.js";
export default {
  mixins: [fetchData({})],
  name: "BlogComment",
  components: {
    MessageArea,
  },
  data() {
    return {
      loadCommentMore: false,
      noMore: false,
      commentPage: {
        page: 1,
        limit: 10,
      },
    };
  },
  created() {
    this.debounceHandlerScrool = debounce(this.handlerScroll, 500);
    this.$eventBus.$on("mainScroll", this.debounceHandlerScrool);
  },
  destroyed() {
    this.$eventBus.$off("mainScroll", this.debounceHandlerScrool);
  },
  computed: {
    ishasMore() {
      return this.data.rows.length < this.data.total;
    },
  },
  methods: {
    async fetchData() {
      const { id } = this.$route.params;
      const res = await getBlogComment({ blogId: id, ...this.commentPage });
      return res?.data || {};
    },
    async fetchMore() {
      if (!this.ishasMore) {
        this.noMore = true;
        return;
      }
      this.loadCommentMore = true;
      this.commentPage.page++;
      const res = await this.fetchData();
      this.data.total = res?.total || 0;
      this.data.rows = this.data.rows.concat(res?.rows || []);
      this.loadCommentMore = false;
    },
    async handleSubmit(commentInfo, callback) {
      const res = await postBlogComment({
        ...commentInfo,
        blogId: this.$route.params?.id,
      });
      if (!res) {
        callback("评论失败了...");
        return;
      }
      this.data.rows.unshift(res.data);
      callback();
      this.$showMessage({
        content: "评论成功",
        type: "success",
      });
    },
    async handlerScroll(mainScroll) {
      if (this.loadCommentMore) {
        return;
      }
      const scrollHeight = mainScroll.scrollHeight;
      const scrollTop = mainScroll.scrollTop;
      const clientHeight = mainScroll.clientHeight;
      if (scrollHeight - (scrollTop + clientHeight) < 100) {
        await this.fetchMore();
      }
    },
  },
};
</script>

<style scoped lang="less">
@import "@/styles/var.less";
.blogcomment-container {
  .nomore-text {
    font-size: 12px;
    text-align: center;
    color: @gray;
    margin-top: 20px;
  }
}
</style>
